/**
 * @author 03010570
 * @date 2020/06/16
 * describe:    LeetCode:  面试题 29、顺时针打印矩阵
 */
public class LeetCode_29 {
    public static void main(String[] args) {
        int[][] ints = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[] spiralOrder = spiralOrder2(ints);
        for (int i : spiralOrder) {
            System.out.print(i + " , ");
        }
    }

    public static int[] spiralOrder2(int[][] matrix) {
        if(matrix.length==0 || matrix[0].length==0){
            return new int[0];
        }
        int row = matrix.length;
        int column = matrix[0].length;
        int[] result = new int[row * column];
        int left = 0, right = column - 1, top = 0, bottom = row - 1;
        int index = 0;
        while (left <= right && top <= bottom) {
            // 上边：从左到右循环
            for (int currColumn = left; currColumn <= right; currColumn++) {
                result[index++] = matrix[top][currColumn];
            }
            // 右边：从上到下循环
            for (int currRow = top + 1; currRow <= bottom; currRow++) {
                result[index++] = matrix[currRow][right];
            }
            if (left < right && top < bottom) {
                // 下边：从右到左循环
                for (int currColumn = right - 1; currColumn > left; currColumn--) {
                    result[index++] = matrix[bottom][currColumn];
                }
                // 左边边：从下到上循环
                for (int currRow = bottom; currRow > top; currRow--) {
                    result[index++] = matrix[currRow][left];
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return result;

    }

    public static int[] spiralOrder(int[][] matrix) {
        int row = matrix.length;
        int column = matrix[0].length;
        int[] result = new int[row * column];
        int[] record = {0, column - 1, 0, row - 1};
        int index = 0;
        while (record[0] <= record[1] && record[2] <= record[3]) {
            for (int i = record[0]; i < record[1]; i++) {
                result[index++] = matrix[record[2]][i];
            }
            for (int j = record[2] + 1; j < record[3]; j++) {
                result[index++] = matrix[j][record[1]];
            }
            if (record[0] < record[1] && record[2] < record[3]) {
                for (int i = record[1] - 1; i > record[0]; i--) {
                    result[index++] = matrix[record[3]][i];
                }
                for (int j = record[3]; j > record[2]; j--) {
                    result[index++] = matrix[j][record[0]];
                }
            }
            record[0]++;
            record[1]--;
            record[2]++;
            record[3]--;
        }
        return result;

    }
}
